#pragma once

#include <queue>
#include <iostream>
#include <string>
#include <mutex>
#include <pthread.h>

const static int defaultcap = 100;

template<typename T>
class BlockQueue
{
private:
    bool Empty()
    {
        return _block_queue.empty();
    }

    bool Full()
    {
        return _block_queue.size() == max_cap;
    }
public:
    BlockQueue(int cap = defaultcap) :max_cap(cap)
    {
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        pthread_mutex_init(&_mutex, nullptr);
    }

    void Pop(T* t)
    {
        pthread_mutex_lock(&_mutex);
        while(Empty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        *t = _block_queue.front();
        _block_queue.pop();
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
    }

    void Enter(const T& t)
    {
        pthread_mutex_lock(&_mutex);
        while(Full())
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _block_queue.push(t);
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_c_cond);
    }

    ~BlockQueue()
    {
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
        pthread_mutex_destroy(&_mutex);
    }
private:
    int max_cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;
    std::queue<T> _block_queue;
};